
import util from '@/libs/util';
import CONSTANTS from '@/config/constants';
import Cookies from 'js-cookie';
import vSwitch from '@/util/vSwitch.vue';
import myUtil from '../../util/formReg';

export default {
    components: {
        vSwitch
    },
    data () {
        return {
            columns: [{
                title: '账号',
                key: 'loginid'
            }, {
                title: '名称',
                key: 'name'
            }, {
                title: '联系手机',
                key: 'cellphone'
            }, {
                title: '状态',
                key: 'status',
                render: (h, params) => {
                    return h(vSwitch, {
                        props: {
                            vStatus: params.row.status === 1
                        },
                        on: {
                            input: (switchVal) => {
                                // this.changeStatus(params.row, switchVal);
                            }
                        }
                    });
                }
            }, {
                title: '操作',
                key: 'action',
                width: 300,
                align: 'center',
                render: (h, params) => {
                    return h('div', [
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.setRoleList(params.row.id);
                                }
                            }
                        }, '分配权限'),
                        /* h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.detail(params.row.id);
                                    }
                                }
                            }, '详情'), */
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.$refs['formData'].resetFields();
                                    this.showEdit(params.row.id);
                                }
                            }
                        }, '修改'),
                        h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            on: {
                                click: () => {
                                    this.delete(params.row.id);
                                }
                            }
                        }, '删除')
                    ]);
                }
            }],
            data: [],

            formData: {

            },
            modalVisible: false,
            saveModalVisible: false,
            total: 0,
            pageIndex: 1,
            pageSize: 10,
            roleModal: false,
            allRole: [],
            roleList: [],
            orgList: [],
            depList: [],
            titles: ['可添加角色', '已添加角色'],
            listStyle: {
                height: '350px'
            },
            userId: '',
            orgTree: [],
            depTree: [],
            baseuser: JSON.parse(Cookies.get('baseUser')),
            query: {},
            depName: '',
            queryData: {
                orgId: '',
                depId: '',
                name: ''
            },
            options: {
                shortcuts: [{
                    text: '今天',
                    value () {
                        return new Date();
                    }
                }]
            },
            isRead: true,
            depTreeVisible: false,
            roles: [1],
            areaList: [],
            formDataRules: {// 添加班级表单验证规则
                areaId: [
                    { required: true, message: '请选择归属区域', trigger: 'change', type: 'number' }
                    // { required: true, validator: this.doTest ,trigger: 'change'}
                ],
                orgId: [
                    { required: true, message: '请选择归属机构', trigger: 'change', type: 'number'}
                ],
                depId: [
                    { required: true, message: '请选择归属部门', trigger: 'change', type: 'number'}
                ],
                name: [
                    { type: 'string', required: true, message: '请输入姓名', trigger: 'blur'}
                ],
                loginid: [
                    { type: 'string', required: true, message: '请输入登录名', trigger: 'blur'},
                    { type: 'string', max: 20, message: '用户名过长！不能超过20个字符', trigger: 'blur' }
                ],
                passwordShow: [
                    { required: true, message: '请输入密码', trigger: 'blur', type: 'string'},
                    { type: 'string', max: 20, message: '密码不能超过20个字符', trigger: 'blur' },
                    { required: true, validator: this.inputPwd, trigger: 'blur'}
                ],
                passwordRe: [
                    { required: true, message: '请再次输入密码', trigger: 'blur', type: 'string'},
                    { type: 'string', max: 20, message: '密码不能超过20个字符', trigger: 'blur' },
                    { required: true, validator: this.inputPwd, trigger: 'blur'}
                ],
                cellphone: [
                    { required: true, message: '请输入联系手机', trigger: 'blur', type: 'string' },
                    { required: true, validator: myUtil.regPhone, trigger: 'blur'}
                    // {message: '请输入正确的手机', trigger: 'blur', pattern: '/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$/' }
                ],
                email: [
                    { message: '请输入正确的邮箱', trigger: 'blur', type: 'email'}
                ],
                classTimeJson: [
                    { required: true, message: '请确认课次', trigger: 'blur'}
                ],
                classScheduleJson: [
                    { required: true, message: '请确认课表', trigger: 'blur'}
                ],
                classApplyType: [
                    { required: true, message: '请选择录取方式', trigger: 'blur', type: 'number'}
                ],
                // areaIds: [
                //     {required: true, message: '请选择用户校区', trigger: 'change', type: 'array'}
                // ]
            }
        };
    },
    mounted () {
        this.loadList();
        this.loadTree();
        util.ajax.post('/base/organize/findOrgByType', util.toFormData({
            type: 1
        })).then(res => { // 获得机构
            this.orgList = res.data.data;
        });

        util.ajax.post('/base/datadictionary/findByCode', util.toFormData(// 获得区域
            {CODE: 'AREA_TYPE'}
        )).then(res => {
            if (res.data.code == 200) {
                var data = res.data.data;
                this.areaList = data;
            } else {
                this.$Message.error(res.data.message);
            }
        });
    },
    methods: {
        whenSelectRolesItem: function (events) {
            console.log(events);
        },
        whenSelectOrg: function (event) {
            util.ajax.post('base/organize/getDepByOrgIdExceptOrg', util.toFormData({
                id: event
            })).then(res => {
                this.depList = res.data.data;
            });
        },
        loadList: function (orgId, depId) {
            var type = this.baseuser.type;
            if (type == 1) {
                util.ajax.post(CONSTANTS.USER_LIST, util.toFormData({
                    page: this.pageIndex,
                    size: this.pageSize,
                    orgId: '',
                    depId: '',
                    name: this.queryData.name
                })).then(res => {
                    this.data = res.data.data.list;
                    this.total = res.data.data.total;
                });
            } else {
                if (orgId == undefined) {
                    this.queryData.orgId = this.baseuser.orgId;
                } else {
                    this.queryData.orgId = orgId;
                }

                if (depId == undefined) {
                    this.queryData.depId = this.baseuser.depId;
                } else {
                    this.queryData.depId = depId;
                }

                util.ajax.post(CONSTANTS.USER_LIST, util.toFormData({
                    page: this.pageIndex,
                    size: this.pageSize,
                    orgId: this.queryData.orgId,
                    depId: this.queryData.depId,
                    name: this.queryData.name
                })).then(res => {
                    this.data = res.data.data.list;
                    this.total = res.data.data.total;
                });
            }
        },
        detail (id) {
            util.ajax.post(CONSTANTS.USER_DETAIL, util.toFormData({
                id: id
            })).then(res => {
                if (res.data.data) {
                    this.formData = res.data.data;
                    this.modalVisible = true;
                } else {
                    this.$Modal.error({
                        title: '警告',
                        content: '出错了'
                    });
                }
            });
        },
        showAdd () {
            this.formData = {};
            this.saveModalVisible = true;
            this.isRead = false;
        },
        showEdit (id) {
            this.formData = {};
            util.ajax.post('/base/user/detail', util.toFormData({
                id: id
            })).then(res => { // 用户详情;
                let data = res.data.data;
                util.ajax.post('base/organize/getDepByOrgIdExceptOrg', util.toFormData({
                    id: data.orgId
                })).then(res => {
                    this.depList = res.data.data;
                    if (data.depId != null && data.depId != '') {
                        data.depId = parseInt(data.depId);
                    }
                    // if (data.areaIds) {
                    //     let ids = data.areaIds.split('@');
                    //     data.areaIds = [];
                    //     if (ids && ids.length > 0) {
                    //         for (let i in ids) {
                    //             data.areaIds.push(parseInt(ids[i]));
                    //         }
                    //     }
                    // } else {
                    //     data.areaIds = [];
                    // }
                    this.formData = data;
                });
            });
            this.saveModalVisible = true;
        },
        userSave (name) {
            let formData = this.formData;
            let _this = this;
            this.$refs[name].validate((valid) => { // 表单验证
                if (valid) {
                    // if (_this.formData.areaIds && _this.formData.areaIds.length > 0) {
                    //     _this.formData.areaIds = _this.formData.areaIds.join('@');
                    // }
                    util.ajax.post('/base/user/save', util.toFormData(
                        formData
                    )).then(res => {
                        if (res.data.code == 200) {
                            this.$Message.success('保存成功！');
                            this.saveModalVisible = false;
                            this.loadList();
                        } else {
                            this.$Message.error(res.data.message);
                        }
                    }).then(function () {
                        _this.$refs['formData'].resetFields();
                    });
                }
            });
            // let formData = this.formData;
            // let passwordShow = formData.passwordShow;
            // let passwordRe = formData.passwordRe;
            // if (passwordShow != passwordRe) {
            //     this.$Message.error('输入密码不一致！');
            //     return;
            // }
            // formData.password = formData.passwordShow;
            // util.ajax.post('/base/user/save', util.toFormData(
            //     formData
            // )).then(res => {
            //     if (res.data.code == 200) {
            //         this.$Message.success('保存成功！');
            //     } else {
            //         this.$Message.error(res.data.message);
            //     }
            //     this.saveModalVisible = false;
            //     this.formData = {};
            //     this.loadList();
            // });
        },
        delete (id) {
            this.$Modal.confirm({
                title: '提示',
                content: '<p>确定删除？</p>',
                onOk: () => {
                    util.ajax.post('/base/user/delete', util.toFormData({id: id})).then(res => {
                        if (res.data.code == 200 && res.data.message == 'SUCCESS') {
                            this.$Message.success('操作成功！');
                            this.loadList();
                        } else {
                            this.$Message.success('操作失败！');
                        }
                    });
                },
                onCancel: () => {
                }
            });
        },
        setRoleList (id) {
            this.userId = id;
            util.ajax.post('/base/user/getRole').then(res => {
                if (res.data.data) {
                    let allRole = [];
                    let roleList = res.data.data.roleList;
                    res.data.data.allRole.forEach((item, index) => {
                        allRole.push({
                            key: item.id,
                            label: item.name
                        });
                    });
                    this.allRole = allRole;
                    this.roleList = roleList.map(item => item.roleId);
                    this.roleModal = true;
                } else {
                    this.$Modal.error({
                        title: '警告',
                        content: res.data.message
                    });
                }
            });
        },
        filterMethod (data, query) {
            return data.label.indexOf(query) > -1;
        },
        handleChange (newTargetKeys) {
            this.roleList = newTargetKeys;
        },
        roleSave () {
            let roleList = this.roleList;
            util.ajax.post('/base/user/saveRole', util.toFormData({
                userId: this.userId,
                roleList: roleList
            })).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.roleModal = false;
                    this.$Message.success('保存成功！');
                    this.loadList();
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
        },
        treeSelect (res) {
            res[0].id = res[0].id + '';
            if (res.length == 3) { // 机构的id为三位
                this.loadList(res[0].id, undefined);
            } else {
                this.loadList(undefined, res[0].id);
            }
            // 根据当前选择部门找到所有父部门
            // var id = res[0].id;
            // util.ajax.post('/base/organize/findDepByDepId', util.toFormData({
            //     depId: id
            // })).then(res => {
            //     let list = res.data.data;
            //     let s = '';
            //     for (let i in list) {
            //         if (i == 0) {
            //             s += list[i].id;
            //         } else {
            //             s += '@' + list[i].id;
            //         }
            //     }
            //     util.ajax.post(CONSTANTS.USER_LIST, util.toFormData({
            //         page: '1',
            //         size: '10',
            //         orgId: '',
            //         depId: s
            //     })).then(res => {
            //         this.data = res.data.data.list;
            //         this.total = res.data.data.total;
            //     });
            // });
        },
        loadTree: function () {
            let roles = this.baseuser.roles;
            var id = this.baseuser.depId;
            var type = this.baseuser.type;
            if (type == 1) {
                util.ajax.post('/base/organize/findOrgAll', util.toFormData({
                    orgid: ''
                })).then(res => {
                    if (res.data.data) {
                        let tree = [];
                        var dataList = res.data.data;
                        if (this.baseuser.type === 2) {
                            for (var i in dataList) {
                                let item = dataList[i];
                                if (item.id == this.baseuser.orgId) {
                                    tree.push({
                                        id: item.id,
                                        title: item.name,
                                        expand: true,
                                        children: []
                                    });
                                }
                            }
                        } else {
                            for (var i in dataList) {
                                let item = dataList[i];
                                if (item.parentid == 0) {
                                    tree.push({
                                        id: item.id,
                                        title: item.name,
                                        expand: true,
                                        children: []
                                    });
                                }
                            }
                        }
                        if (tree.length > 0) {
                            this.createTree(tree, dataList);
                        }
                        this.orgTree = tree;
                    }
                });
            } else {
                for (let i in roles) {
                    let item = roles[i];
                    if (item.name.indexOf('管理员') > 0) {
                        id = this.baseuser.orgId;
                    }
                }
                util.ajax.post('/base/organize/getDepByOrgId', util.toFormData({
                    id: id
                })).then(res => {
                    if (res.data.data) {
                        let tree = [];
                        var dataList = res.data.data;
                        if (this.baseuser.type === 2) {
                            for (var i in dataList) {
                                let item = dataList[i];
                                if (item.id == this.baseuser.orgId) {
                                    tree.push({
                                        id: item.id,
                                        title: item.name,
                                        expand: true,
                                        children: []
                                    });
                                }
                            }
                        } else {
                            for (var i in dataList) {
                                let item = dataList[i];
                                if (item.parentid == 0) {
                                    tree.push({
                                        id: item.id,
                                        title: item.name,
                                        expand: true,
                                        children: []
                                    });
                                }
                            }
                        }
                        if (tree.length > 0) {
                            this.createTree(tree, dataList);
                        }
                        this.orgTree = tree;
                    }
                });
            }
        },
        createTree (tree, data) {
            let childTree = [];
            let _this = this;
            tree.forEach(treeItem => {
                childTree = [];
                data.forEach(dataItem => {
                    if (treeItem.id === dataItem.parentid) {
                        childTree.push({
                            id: dataItem.id,
                            title: dataItem.name,
                            expand: true,
                            children: []
                        });
                    }
                });
                if (childTree.length > 0) {
                    treeItem.children = childTree;
                    _this.createTree(childTree, data);
                }
            });
        },
        whenTapDep: function () {
            this.depTreeVisible = true;
            util.ajax.post('/base/organize/findOrgAll', util.toFormData({
                orgid: ''
            })).then(res => {
                if (res.data.data) {
                    let tree = [];
                    res.data.data.forEach(item => {
                        if (item.parentid == 0) {
                            tree.push({
                                id: item.id,
                                title: item.name,
                                expand: true,
                                children: []
                            });
                        }
                    });
                    if (tree.length > 0) {
                        this.createTree(tree, res.data.data);
                    }
                    this.depTree = tree;
                }
            });
        },
        whenSelectDepTree: function (res) {
            var id = res[0].id;
            var name = res[0].title;
            this.formData.depId = id;
            this.depName = name;
        },
        inputPwd: function (rule, value, callback, source) { // 验证两次输入的密码
            for (let i in source) {
                if (i == 'passwordShow') {
                    let passwordRe = this.formData.passwordRe;
                    if (passwordRe && passwordRe != source[i]) {
                        callback(new Error('两次输入密码不一致！'));
                    } else {
                        callback();
                    }
                } else if (i == 'passwordRe') {
                    let passwordShow = this.formData.passwordShow;
                    if (passwordShow && passwordShow != source[i]) {
                        callback(new Error('两次输入密码不一致！'));
                    } else {
                        callback();
                    }
                }
            }
        },
    }
};
